<?php

Page_startup($title,$version);

if (is_writable('config.install.php') && is_writable('config.mysql.php')) {
	if (empty($_GET)) { ?>
		<p>Please specify your MySQL server info:
		<form method="post" action="index.php?db">
		Server: <input type="text" name="server" value="localhost" /><br />
		Database: <input type="text" name="database" value="featherchat" /><br />
		User: <input type="text" name="user" /><br />
		Password: <input type="password" name="password" /><br />
		<input type="Submit" value="Go">
		</form>
		</p><?php
	}
	elseif(isset($_GET[db])) {

		$link = MySQL_go($_POST[server],$_POST[user],$_POST[password]);
		mysql_select_db($_POST[database]) or ($nodb = 1);

		$server = mysql_real_escape_string($_POST[server]);
		$database = mysql_real_escape_string($_POST[database]);
		$user = mysql_real_escape_string($_POST[user]);
		$password = mysql_real_escape_string($_POST[password]);

		if ($nodb) { // Check if the database exists.  If not, try to create it.  Let us know if there are problems.
			echo "DB does not exist, creating...<br />";
			$createdbsql = "CREATE DATABASE `".$database."`";
			mysql_query($createdbsql) or die ("Unable to create database: ".mysql_error());
			mysql_select_db($database);
		}
		else { // Since we know the database already existed, we better test to make sure it doesn't already have these tables.
			$tablessql = "SHOW TABLES";
			$result = mysql_query($tablessql);

			$i=0;
			while($table = mysql_fetch_row($result)) { 
				$tables_r[$i] = $table[0];
				$i++;
			}

			if (count($tables_r) > 0) {
				foreach($tables_r as $table) {
					if (stristr($table,"featherchat") == TRUE) {
						$tablesexist = 1;
					}
				}
			}
		}

		if ($tablesexist != "1") {
			echo "Creating tables...<br />";
			
			$createtable1sql = "CREATE TABLE `".$database."`.`featherchat_messages` (
			`message` text NOT NULL ,
			`user` varchar( 12 ) NOT NULL ,
			`timestamp` int( 11 ) UNSIGNED NOT NULL ,
			`msgid` smallint( 6 ) NOT NULL
			)";
			$createtable2sql = "CREATE TABLE `".$database."`.`featherchat_users` (
			`name` varchar( 16 ) NOT NULL ,
			`pass` varchar( 32 ) NOT NULL ,
			`level` tinyint( 4 ) NOT NULL default '0',
			`history` tinyint( 4 ) NOT NULL default '5',
			`histmin` smallint( 6 ) NOT NULL default '3',
			`email` varchar( 128 ) NOT NULL ,
			`emailnot` tinyint( 1 ) NOT NULL default '0',
			`emailtime` smallint( 6 ) NOT NULL default '30',
			`lastseen` bigint( 11 ) UNSIGNED NOT NULL default '1',
			`notified` bigint( 11 ) UNSIGNED NOT NULL default '0',
			`refresh` SMALLINT( 6 ) NOT NULL DEFAULT '0',
			`timezone` TINYINT( 2 ) NOT NULL DEFAULT '-5',
			`showtime` TINYINT( 1 ) NOT NULL DEFAULT '1'
			)";
			$createtable3sql = "CREATE TABLE `".$database."`.`featherchat_tokens` (
			`user` char( 16 ) NOT NULL ,
			`tokenid` char( 32 ) NOT NULL ,
			`timestamp` int ( 11 ) UNSIGNED NOT NULL
			)";
			$createtable4sql = "CREATE TABLE `".$database."`.`featherchat_settings` (
			`db_version` TINYINT NOT NULL DEFAULT '1',
			`email_enable` TINYINT( 1 ) NOT NULL DEFAULT '0',
			`email_user` VARCHAR( 32 ) NOT NULL ,
			`email_pass` VARCHAR( 32 ) NOT NULL ,
			`email_host` VARCHAR( 32 ) NOT NULL ,
			`email_port` SMALLINT( 5 ) NOT NULL ,
			`featherchataddr` VARCHAR( 128 ) NOT NULL ,
			`timezone` TINYINT( 2 ) NOT NULL DEFAULT '-5'
			)";

			mysql_query($createtable1sql);
			mysql_query($createtable2sql);
			mysql_query($createtable3sql);
			mysql_query($createtable4sql);
		} else { echo "Tables exist, skipping...<br />"; }

		$file = fopen ("config.mysql.php","r+");
		ftruncate($file,0);
		fwrite($file,"<?php\n\$mysql_server = '".$server."';\n\$mysql_db = '".$database."';\n\$mysql_user = '".$user."';\n\$mysql_pass = '".$password."';\n?>\n");
		fclose($file);

		?><p>Please choose your Administrator info:
		<form method="post" action="index.php?admin">
		Username: <input type="text" name="adminuser" /><br />
		Password: <input type="password" name="adminpass" /><br />
		<input type="Submit" value="Go">
		</form>
		</p><?php
			
		mysql_close($link);
	}
	elseif (isset($_GET[admin])) {

		if ((!empty($_POST[adminuser])) && (!empty($_POST[adminpass]))) {

			require 'config.mysql.php';

			$link = MySQL_go($mysql_server,$mysql_user,$mysql_pass);
			mysql_select_db($mysql_db);

			$adminuser = mysql_real_escape_string($_POST[adminuser]);
			$adminpass = mysql_real_escape_string($_POST[adminpass]);

			$checkadminsql = "SELECT `name` FROM `featherchat_users`";
			$result = mysql_query($checkadminsql);
			$query = @mysql_result($result,0);

			if (!empty($query)) {
				echo "An admin was already found, dropping...";
				
				$dropoldadminsql = "TRUNCATE `featherchat_users`";
				mysql_query($dropoldadminsql) or die ("Unable to drop admin.");
			}

			$addadminsql = "INSERT INTO `featherchat_users` (`name` ,`pass` ,`level`) VALUES ('".$adminuser."', '".md5($adminpass)."', '1')";
			mysql_query($addadminsql) or die ("Unable to create admin! ".mysql_error());
			echo "Admin \"".$_POST[adminuser]."\" created.<br /><br />";

			$pear = Check_for_PEAR_Mail();
		
			if ($pear == "1") {
				 Email_config_form($_SERVER[PHP_SELF]."?mail",$mysql_server,$mysql_user,$mysql_pass,$mysql_db);			
			}
			else {
				echo "FeatherChat was unable to detect a PEAR Mail installation.  If you would like to use e-mail notification, see <a href=\"http://pear.php.net/packages.php?catpid=14&catname=Mail\">here</a> and then visit the Options page within FeatherChat.<br /><a href=\"".$_SERVER[PHP_SELF]."?mail\">Next</a>";
			}

			mysql_close($link);
		}
		else { echo "You left something blank. Go back."; }
	}
	elseif (isset($_GET[mail])) {

		$pear = Check_for_PEAR_Mail();

		if (($_POST[enable] == "on") && ($pear == 1)) { $enable = 1; } else { $enable = 0; }
		if (($enable == 1) && (empty($_POST[featherchataddr]))) {
			echo "FeatherChat installation address cannot be left blank.";
			die;
		}

		require 'config.mysql.php';
		$link = MySQL_go($mysql_server,$mysql_user,$mysql_pass);
		mysql_select_db($mysql_db) or die ("Unable to connect to database:".mysql_error());

		$email_user = mysql_real_escape_string($_POST[emailuser]);
		$email_pass = mysql_real_escape_string($_POST[emailpass]);
		$email_host = mysql_real_escape_string($_POST[emailhost]);
		$email_port = mysql_real_escape_string($_POST[emailport]);
		$featherchataddr = mysql_real_escape_string($_POST[featherchataddr]);
		$mailsql = "INSERT INTO `featherchat_settings` (`email_enable`,`email_user` ,`email_pass` ,`email_host`,`email_port`,`featherchataddr`) VALUES ('".$enable."', '".$email_user."', '".$email_pass."', '".$email_host."', '".$email_port."', '".$featherchataddr."')";
		mysql_query($mailsql) or die ("Unable to insert mail data: ".mysql_error());

		$varstring = "<?php\n\$installed = '1';\n?>";
		$file = fopen("config.install.php","r+");
		ftruncate($file,0);
		fwrite($file,$varstring);
		fclose($file);

		echo "Installation complete!<br />";
		Home_link();
	}
}
else { echo "config.install.php and config.mysql.php must be writable.<br />Please ensure that the webserver's user has write access to vars.php<br/ >See README for more information."; }


Page_shutdown();